package factory.one.controller;

import factory.one.entity.Product;
import factory.one.pojo.common.Page;
import factory.one.pojo.common.SqlCondition;
import factory.one.service.ProductService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.sql.Types;
import java.util.Collections;
import java.util.List;

/**
 * @author sk.z
 * 2023/7/20
 * 产品
 **/
@Controller
@RequestMapping("/product")
public class ProductController {

    private final ProductService productService;

    public ProductController(ProductService productService) {
        this.productService = productService;
    }

    @GetMapping("/add.html")
    public String addHtml(){
        return "product/add";
    }

    @ResponseBody
    @PostMapping("/add")
    public String add(@RequestParam String name){
        Product product = new Product();
        product.setName(name);
        product.setStatus(1);
        return productService.add(product).toString();
    }

    @GetMapping("/list.html")
    public String listHtml(@RequestParam(defaultValue = "1") Integer page,
                           @RequestParam(defaultValue = "30") Integer size,
                           Model model) {
        SqlCondition condition = new SqlCondition("status = ?", 1, Types.INTEGER);
        int count = productService.countByCondition(Collections.singletonList(condition));
        List<Product> list = productService.listByCondition(page, size,Collections.singletonList(condition));
        model.addAttribute("page", new Page<>(list, count, page, size));
        return "product/list";
    }

    @GetMapping("/edit.html")
    public String editHtml(@RequestParam Long productId, Model model){
        model.addAttribute("product",productService.getById(productId));
        return "product/edit";
    }

    @ResponseBody
    @PostMapping("/edit")
    public Integer edit(Product product){
        return productService.update(product);
    }

    @GetMapping("del")
    public String del(Long productId, Model model){
        productService.del(productId);
        return listHtml(1,30, model);
    }

}
